from db import DB
import json


class UseItem():
    """
    使用道具/装备类
    params:
        unit: [obj] 单位对象
    """

    def __init__(self, unit):
        self.unit = unit

    def use(self, id):
        """
        使用道具/装备
        """
        item = DB().get_item_row(id)
        o_name = "无"
        
        if item["type"] > 0:
            for i in range(len(self.unit.equipment) - 1):
                if self.unit.equipment[i]["type"] == item["type"]:
                    o_name = self.unit.equipment[i]["name"]
                    self.unit.use_item(self.unit.equipment[i], -1)
                    del self.unit.equipment[i]
                    break
        
        self.unit.use_item(item, 1)

        if item["type"] > 0:
            self.unit.equipment.append(item)

            return "将装备 <span style='color:orange'>[%s]</span> 替换成了 <span style='color:green'>[%s]</span>" % (o_name, item["name"])
        
        return "使用了道具 <span style='color:green'>[%s]</span>" % item["name"]
        
    def r(self, id):
        use = self.use(id)

        use_info = {
            "use_log": use,
            "player": {
                "level": self.unit.level,
                "exp": self.unit.exp,
                "max_exp": self.unit.max_exp,
                "hp": self.unit.hp,
                "atk": self.unit.atk,
                "defense": self.unit.defense,
                "hit": self.unit.hit,
                "dod": self.unit.dod,
                "cri": self.unit.cri,
                "skill": self.unit.skill,
                "equipment": self.unit.equipment,
            }
        }

        return use_info

